package com.schoolgard.action.configuration;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.schoolegard.services.DeviceService;
import com.schoolegard.services.OrganizationService;
import com.schoolegard.services.ParamAccessService;
import com.schoolegard.services.ParamCameraService;
import com.schoolegard.services.RegionsService;
import com.schoolegard.services.TerminalService;
import com.schoolgard.base.BaseAction;
import com.schoolgard.entitybean.Device;
import com.schoolgard.entitybean.Organization;
import com.schoolgard.entitybean.ParamAccess;
import com.schoolgard.entitybean.ParamCamera;
import com.schoolgard.entitybean.Regions;
import com.schoolgard.entitybean.Terminal;

public class TerminalSettingAction extends BaseAction{
    
	private static Logger logger = Logger.getLogger(TerminalSettingAction.class);
	private static final long serialVersionUID = 201203152228L;
	
	
	private ParamCameraService paramCameraService;
	private ParamAccessService paramAccessService;
	private RegionsService regionsService;
	private OrganizationService organizationService;
	private DeviceService deviceService;
	private TerminalService terminalService;
	
	private ParamAccess paccess;
	private ParamCamera pcmera;
	
	/**
	 * 刷卡终端参数获取
	 */
	public void findByAccessTerminalId()
	{
		String terminalId = request.getParameter("accessTerminalId");
		ParamAccess pas = paramAccessService.findById(terminalId.replace("te_", ""));
		writeToResponse(JSONObject.fromObject(pas).toString());
	}
	/**
	 * 摄像头终端数据获取
	 */
	public void findByCameraTerminalId()
	{
		String terminalId = request.getParameter("cameraTerminalId");
		ParamCamera pac = paramCameraService.findById(terminalId.replace("te_", ""));
		writeToResponse(JSONObject.fromObject(pac).toString());
	}
	
	/**
	 * 保存刷卡终端数据
	 */
	public void saveParamAccess()
	{
		String terminalId = request.getParameter("terminalId");
		if(StringUtils.isBlank(terminalId)){
			writeToResponse("0");
			return;
		}
		String[] teArray = terminalId.split(","); //获得数组
		Set<String> ida = filterID(teArray); //获取所有设备和终端id
		Iterator<String> it = ida.iterator();
		ParamAccess paramAccess = null;
		while(it.hasNext()){
			String id = it.next().replace("te_", "");
			paramAccess = paramAccessService.findById(id);
			Terminal terminal = terminalService.findById(id);
			if(paramAccess == null){
				paramAccess = new ParamAccess();
				paramAccess.setGuid(id);
			}
			if(terminal.getHdType().getName().indexOf("刷卡") != -1){
				paramAccess.setDi1(paccess.getDi1());
				paramAccess.setDi2(paccess.getDi2());
				paramAccess.setDo1(paccess.getDo1());
				paramAccess.setDo2(paccess.getDo2());
				paramAccess.setManagerServerIp(paccess.getManagerServerIp());
				paramAccess.setName(paccess.getName());
				paramAccess.setPwd(paccess.getPwd());
				paramAccess.setTerminal(terminal);
				paramAccess.setUserName(paccess.getUserName());
			}else{
				continue;
			}
			try{
				paramAccessService.saveOrUpdate(paramAccess);
			}catch (Exception e) {
				e.printStackTrace();
				writeToResponse("0");
				break;
			}
		}
		writeToResponse("1");
	}
	
	/**
	 * 保存摄像终端数据
	 */
	public void saveParamCamera()
	{
		String terminalId = request.getParameter("terminalId");
		if(StringUtils.isBlank(terminalId)){
			writeToResponse("0");
			return;
		}
		String[] teArray = terminalId.split(","); //获得数组
		Set<String> ida = filterID(teArray); //获取所有设备和终端id
		Iterator<String> it = ida.iterator();
		ParamCamera paramCamera = null;
		while(it.hasNext()){
			String id = it.next().replace("te_", "");
			paramCamera = paramCameraService.findById(id);
			Terminal terminal = terminalService.findById(id);
			if(paramCamera == null){
				paramCamera = new ParamCamera();
				paramCamera.setGuid(id);
			}
			if(terminal.getHdType().getName().indexOf("摄像") != -1){
				paramCamera.setDi1(pcmera.getDi1());
				paramCamera.setDi2(pcmera.getDi2());
				paramCamera.setDo1(pcmera.getDo1());
				paramCamera.setDo2(pcmera.getDo2());
				paramCamera.setManagerServerIp(pcmera.getManagerServerIp());
				paramCamera.setMotionAreaRange1(pcmera.getManagerServerIp());
				paramCamera.setMotionAreaSst1(pcmera.getMotionAreaSst1());
				paramCamera.setName(pcmera.getName());
				paramCamera.setPresetDefaultAddress(pcmera.getPresetDefaultAddress());
				paramCamera.setProtocolId(pcmera.getProtocolId());
				paramCamera.setProtocolMode(pcmera.getProtocolMode());
				paramCamera.setProtocolSpeed(pcmera.getProtocolSpeed());
				paramCamera.setPwd(pcmera.getPwd());
				paramCamera.setTerminal(terminal);
				paramCamera.setUserName(pcmera.getUserName());
			}else{
				continue;
			}
			try{
				paramCameraService.saveOrUpdate(paramCamera);
			}catch (Exception e) {
				e.printStackTrace();
				writeToResponse("0");
				break;
			}
			
		}
		writeToResponse("1");
	}
	
	
	private Set<String>  filterID(String[] fa)
	{
		Set<String> deteIds = new HashSet<String>(); //保证不会重复加入id
		for (String id : fa) {
			if(id.indexOf("te_")!=-1){ //终端id直接加进来
				deteIds.add(id);
			}
			if(id.indexOf("re_")!=-1){ //区域
				deteIds.addAll(findByRegions(Long.valueOf(id.replace("re_", ""))));
			}else if(id.indexOf("or_")!=-1){ //组织
				deteIds.addAll(findByOrganization(Long.valueOf(id.replace("or_", ""))));
			}
		}
		return deteIds;
	}
	
	private Set<String> findByRegions(Long regionsId)
	{
		Set<String> deteIds = new HashSet<String>();
		List<Regions> children_regions = regionsService.findListByParentId(regionsId);
		List<Organization> organization = organizationService.findByRegions(regionsId);
		for(int i=0 ; i<organization.size() ; i++){
			deteIds.addAll(findByOrganization(organization.get(i).getId()));
		}
		if(children_regions != null && children_regions.size() > 0){
			for(int j=0 ; j<children_regions.size() ; j++){
				deteIds.addAll(findByRegions(children_regions.get(j).getId()));
			}
		}
		return deteIds;
	}
	
	private Set<String> findByOrganization(Long orgId)
	{
		Set<String> deteIds = new HashSet<String>();
		List<Device> devices = deviceService.findByOrganization(orgId);
		List<Organization> children_org = organizationService.findByParentId(orgId);
		for (Device device : devices) {
			deteIds.addAll(findTerByDevice(device.getGuid())); //终端无需设置
		}
		for(int i= 0 ;i<children_org.size() ; i++){
			deteIds.addAll(findByOrganization(children_org.get(i).getId()));
		}
		return deteIds;
	}
	
	private Set<String> findTerByDevice(String devId)
	{
		Set<String> deteIds = new HashSet<String>();
		List<Terminal> terminals = terminalService.findByDevice(devId);
		for (Terminal terminal : terminals) {
			deteIds.add("te_"+terminal.getGuid());
		}
		return deteIds;
	}
	
	
	
	
	public void setParamCameraService(ParamCameraService paramCameraService) {
		this.paramCameraService = paramCameraService;
	}
	public void setParamAccessService(ParamAccessService paramAccessService) {
		this.paramAccessService = paramAccessService;
	}
	public void setRegionsService(RegionsService regionsService) {
		this.regionsService = regionsService;
	}
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	public void setDeviceService(DeviceService deviceService) {
		this.deviceService = deviceService;
	}
	public void setTerminalService(TerminalService terminalService) {
		this.terminalService = terminalService;
	}
	public ParamAccess getPaccess() {
		return paccess;
	}
	public void setPaccess(ParamAccess paccess) {
		this.paccess = paccess;
	}
	public ParamCamera getPcmera() {
		return pcmera;
	}
	public void setPcmera(ParamCamera pcmera) {
		this.pcmera = pcmera;
	}
	
}
